<?php

namespace App\Admin\Controllers\news;

use App\Admin\Repositories\AdminAdPosition;
use App\Models\AdminAd;
use Dcat\Admin\Admin;
use Dcat\Admin\Form;
use Dcat\Admin\Grid;
use Dcat\Admin\Show;
use Dcat\Admin\Http\Controllers\AdminController;
use Illuminate\Http\Request;
use Illuminate\Support\Collection;

class AdminAdPositionController extends AdminController
{
    /**
     * Make a grid builder.
     *
     * @return Grid
     */
    protected function grid()
    {
        return Grid::make(new AdminAdPosition(), function (Grid $grid) {
            $grid->column('id')->sortable();
            $grid->column('terminal') -> using(trans('admin-ad-position.options.terminal'));
            $grid->column('name');
            $grid->column('status') -> switch();
            $grid->column('created_at');
            $grid->column('updated_at')->sortable();
        });
    }

    /**
     * Make a show builder.
     *
     * @param mixed $id
     *
     * @return Show
     */
    protected function detail($id)
    {
        return Show::make($id, new AdminAdPosition(), function (Show $show) {
            $show->field('id');
            $show->field('terminal');
            $show->field('name');
            $show->field('status');
            $show->field('created_at');
            $show->field('updated_at');
        });
    }

    /**
     * Make a form builder.
     *
     * @return Form
     */
    protected function form()
    {
        return Form::make(new AdminAdPosition(), function (Form $form) {
            $form->display('id');
            $form->text('name')->required();
            $form->radio('terminal')->options(trans('admin-ad-position.options.terminal'))->default('mobile') -> required();
            $form->switch('status')->default(1)->required();

            $form->display('created_at');
            $form->display('updated_at');

            $form->deleting(
                function (Form $form) {
                    $arr = Collection::make($form -> model());

                    $res = AdminAd::firstWhere(['positions_id' => [ 'in' => $arr->pluck('id')->toArray()]]);

                    if($res) {
                        return $form->response()->error('已被新闻占用，无法直接删除');
                    }
                }
            );
        });
    }
}
